// preload.js
const { contextBridge, ipcRenderer, webFrame } = require('electron');

// 导入EventSource库，为Electron提供SSE支持
let EventSource;

try {
    // 尝试加载eventsource模块
    EventSource = require('eventsource');
    console.log('EventSource module loaded successfully');
} catch (error) {
    console.warn('EventSource module not found, using native implementation:', error);
    // 尝试使用更安全的方式获取原生EventSource
    try {
        // 首先检查window.EventSource是否存在
        if (typeof window !== 'undefined' && window.EventSource) {
            EventSource = window.EventSource;
            console.log('Using native EventSource from window');
        } else if (webFrame && webFrame.top && webFrame.top.context) {
            // 尝试使用webFrame作为备选方案
            EventSource = webFrame.top.context.EventSource;
            console.log('Using native EventSource from webFrame');
        } else {
            throw new Error('Native EventSource not available');
        }
    } catch (e) {
        console.error('Failed to get native EventSource:', e);
        // 提供一个更完善的EventSource模拟实现作为后备
        EventSource = class MockEventSource {
            constructor(url, options = {}) {
                this.url = url;
                this.options = options;
                this.readyState = 0;
                this.onopen = null;
                this.onmessage = null;
                this.onerror = null;
                this.onclose = null;
                
                // 尝试使用fetch API模拟SSE行为
                this._simulateSSE();
                console.warn('Mock EventSource created with fetch simulation');
            }
            
            async _simulateSSE() {
                try {
                    const response = await fetch(this.url, {
                        method: 'GET',
                        headers: {
                            'Accept': 'text/event-stream',
                            ...this.options.headers
                        },
                        credentials: this.options.withCredentials ? 'include' : 'omit'
                    });
                    
                    if (response.ok && response.headers.get('content-type')?.includes('text/event-stream')) {
                        this.readyState = 1;
                        if (this.onopen) this.onopen();
                        
                        const reader = response.body.getReader();
                        const decoder = new TextDecoder();
                        let buffer = '';
                        
                        while (true) {
                            const { value, done } = await reader.read();
                            if (done) break;
                            
                            buffer += decoder.decode(value, { stream: true });
                            this._processBuffer(buffer);
                        }
                    } else {
                        throw new Error(`Failed to connect to SSE: ${response.statusText}`);
                    }
                } catch (error) {
                    console.error('SSE simulation error:', error);
                    if (this.onerror) this.onerror(error);
                }
            }
            
            _processBuffer(buffer) {
                const lines = buffer.split('\n');
                let eventData = '';
                let eventType = 'message';
                
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i].trim();
                    if (line.startsWith('data:')) {
                        eventData += line.substring(5).trim() + '\n';
                    } else if (line.startsWith('event:')) {
                        eventType = line.substring(6).trim();
                    } else if (line === '') {
                        if (eventData && this.onmessage) {
                            this.onmessage({
                                type: eventType,
                                data: eventData.trim()
                            });
                        }
                        eventData = '';
                        eventType = 'message';
                    }
                }
            }
            
            close() {
                this.readyState = 2;
                if (this.onclose) this.onclose();
            }
        };
    }
}

// 将安全的API暴露给渲染进程
contextBridge.exposeInMainWorld('electronAPI', {
    // 可以在这里添加需要暴露的API
    // 例如：
    // send: (channel, data) => ipcRenderer.send(channel, data),
    // receive: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(...args))
    
    // 获取应用版本信息
    getAppVersion: () => {
        return process.env.npm_package_version || '1.0.0';
    },
    
    // 检查是否是开发环境
    isDevelopment: () => {
        return process.env.NODE_ENV === 'development';
    },
    
    // 提供EventSource支持，用于SSE功能
    getEventSource: () => EventSource
});

// 保存原始的fetch实现，用于后续增强版fetch实现
const originalFetch = window.fetch;

// 设置全局EventSource对象，使渲染进程可以直接使用
Object.defineProperty(window, 'EventSource', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: EventSource
});

// 保存原始的WebSocket实现
const originalWebSocket = window.WebSocket;

// 确保WebSocket也能正常工作并处理跨域
Object.defineProperty(window, 'WebSocket', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: function(url, protocols) {
        console.log('Creating WebSocket connection to:', url);
        
        // 处理URL协议转换（如果需要）
        let wsUrl = url;
        if (typeof url === 'string') {
            // 确保使用正确的WebSocket协议
            if (url.startsWith('http://')) {
                wsUrl = url.replace('http://', 'ws://');
            } else if (url.startsWith('https://')) {
                wsUrl = url.replace('https://', 'wss://');
            }
        }
        
        // 创建WebSocket选项对象
        let wsOptions = {};
        if (typeof protocols === 'object' && protocols !== null && !Array.isArray(protocols)) {
            // 处理新的WebSocket构造函数参数格式
            wsOptions = protocols;
        }
        
        // 使用原始的WebSocket实现创建实例
        const ws = new originalWebSocket(wsUrl, Array.isArray(protocols) ? protocols : undefined);
        
        // 增强WebSocket实例，添加调试日志和错误处理
        const eventHandlers = {
            open: function() {
                console.log('WebSocket connection opened:', wsUrl);
            },
            message: function(event) {
                // 可以在这里添加消息处理逻辑
                // console.log('WebSocket message received:', event.data);
            },
            error: function(error) {
                console.error('WebSocket error:', error);
            },
            close: function(event) {
                console.log('WebSocket connection closed:', event.code, event.reason);
            }
        };
        
        // 如果是开发环境，添加事件监听器进行调试
        if (process.env.NODE_ENV === 'development') {
            ws.addEventListener('open', eventHandlers.open);
            ws.addEventListener('error', eventHandlers.error);
            ws.addEventListener('close', eventHandlers.close);
        }
        
        return ws;
    }
});


// 增强fetch API以支持流式响应
Object.defineProperty(window, 'fetch', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: async function(url, options = {}) {
        // 自动添加跨域头信息
        const headers = new Headers(options.headers || {});
        
        // 设置默认的Content-Type
        if (!headers.has('Content-Type')) {
            headers.set('Content-Type', 'application/json');
        }
        
        // 合并选项
        const fetchOptions = {
            ...options,
            headers,
            credentials: options.credentials || 'include' // 包含cookie等凭证
        };
        
        try {
            // 调用原始的fetch实现
            const response = await originalFetch(url, fetchOptions);
            
            // 确保响应体可流式处理
            if (response.body && typeof response.body.getReader === 'function') {
                // 原始响应已经支持流式API
                return response;
            } else if (response.body) {
                // 如果响应体不支持getReader，则尝试包装它
                const body = response.body;
                const reader = {
                    getReader: function() {
                        // 这里提供一个简化的reader实现
                        // 注意：这不是真正的流式处理，仅作为后备
                        return {
                            read: async function() {
                                const text = await body.text();
                                return {
                                    done: true,
                                    value: new TextEncoder().encode(text)
                                };
                            }
                        };
                    }
                };
                
                // 返回一个增强的响应对象
                return new Response(reader.getReader(), {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
                });
            }
            
            return response;
        } catch (error) {
            console.error('Fetch error in Electron:', error);
            throw error;
        }
    }
});